﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Threading;

public class UDPNetConnector
{

    public class SendStruct
    {
        public int port;
        public string ip;
        public byte[] data;
    }

    public Queue<SendStruct> msgToSends;
    public Queue<byte[]> msgToReceives;

    private UDPClient udpClient;

    Thread sendThread;
    Thread recvThread;

    bool isAlive;

    public UDPNetConnector(string ip, int port)
    {
        udpClient = new UDPClient((ushort)port, ip, NetManager.bufferSize, OnOneMsgReceived);

        msgToReceives = new Queue<byte[]>();
        msgToSends = new Queue<SendStruct>();
        sendThread = new Thread(SendData);
        recvThread = new Thread(ReceiveData);
    }

    public void Open()
    {
        udpClient.OpenClient();
        isAlive = true;
        sendThread.Start();
        recvThread.Start();
    }

    public void Close()
    {
        udpClient.StopClient();
        isAlive = false;
        sendThread.Abort();
        recvThread.Abort();
    }

    public void SendMessage(byte[] data,int port,string ip)
    {
        SendStruct _dat = new SendStruct();
        _dat.data = data;
        _dat.ip = ip;
        _dat.port = port;
        msgToSends.Enqueue(_dat);
    }

    private void OnOneMsgReceived(byte[] data)
    {
        msgToReceives.Enqueue(data);
        Debug.Log(data.Length);
    }

    private void ReceiveData()
    {
        while (isAlive)
        {
            if (msgToReceives.Count > 0)
            {
                //消息框架发送
                byte[] data_recv = msgToReceives.Dequeue();
                NetManager.Instance.ProcessData(data_recv);
            }


            Thread.Sleep(100);
        }
    }

    private void SendData()
    {
        while (isAlive)
        {
            if (msgToSends.Count > 0)
            {
                lock (msgToSends)
                {
                    SendStruct _sendDat = msgToSends.Dequeue();
                    udpClient.UDPSend(_sendDat.data, _sendDat.ip, _sendDat.port);
                }
            }

            Thread.Sleep(100);
        }
    }

    public void Dispose()
    {
        if (sendThread != null) sendThread.Abort();
        if (udpClient != null) udpClient.StopClient();
        sendThread = null;
        recvThread = null;
        udpClient = null;
    }
}
